package cn.xchats.rpc.common.core;


import cn.xchats.rpc.common.dto.BeanMethod;
import cn.xchats.rpc.common.dto.RequestDto;
import cn.xchats.rpc.common.dto.ResponseDto;
import cn.xchats.rpc.common.type.CodeType;
import cn.xchats.rpc.common.util.ResponseUtil;
import lombok.Getter;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/*
 *缓存BeanMethod
 *@author teddy
 *@date 2018/6/29
 */
public class CacheBeanMethod {

    public static final Map<String, BeanMethod> beanMap = new HashMap<>();//key:类全名+方法名+ '?参数类型'

    @Getter
    private static CacheBeanMethod instance = new CacheBeanMethod();


    /**
     * invoke
     */
    public ResponseDto process(RequestDto request) {
        String method = request.getMethod();
        BeanMethod beanMethod = beanMap.get(method);
        if (null == beanMethod)
            throw new NullPointerException("找不到请求方法");


        Object bean = beanMethod.getBean();
        Method executeMethod = beanMethod.getMethod();
        try {
            Object body = request.getBody();
            Object result;
            if (0 == executeMethod.getParameterTypes().length)
                result = executeMethod.invoke(bean);
            else
                result = executeMethod.invoke(bean, body);
            return ResponseUtil.success(request.getId(), result);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(request.getId(), CodeType.EXECUTE_METHOD_ERROR, e.getMessage());
        }

    }
}
